import axios from "axios";
import qs from "qs";
import { getAccessToken } from '@/utils/accessToken'
/** 返回类型 */
interface Res {
  code: number,
  data: any,
  err: boolean,
  msg: string
}

const service = axios.create({
  baseURL: "/api",
  timeout: 15000,
});

// http request 拦截器
service.interceptors.request.use(
  (config) => {
    if (config.method === "post") {
      config.data = qs.stringify(config.data);
    }
    const token = getAccessToken()
    config.headers["authorization"] = token || ""
    return config;
  },
  (err) => {
    return Promise.reject(err);
  }
);

// get 请求
export const get = (url: string, params = {}) => {
  return new Promise<Res>((resolve, reject) => {
    service
      .get(url, {
        params,
      })
      .then((res) => {
        resolve(res.data);
      })
      .catch((err) => {
        console.log(err);
        reject(err);
      });
  });
}
// post 请求
export const post = (url: string, data = {}) => {
  return new Promise<Res>((resolve, reject) => {
    service.post(url, data).then(
      (res) => {
        resolve(res.data);
      },
      (err) => {
        reject(err);
      }
    );
  });
}
